package tech.veedo.ragdoll;

import cn.hutool.core.util.StrUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tech.veedo.ragdoll.config.PrintMode;
import tech.veedo.ragdoll.processor.ExceptionProcessor;
import tech.veedo.ragdoll.processor.GlobalResponseProcessor;

@Configuration
@EnableConfigurationProperties(RagdollProperties.class)
public class RagdollAutoConfiguration {

    private final RagdollProperties ragdollProperties;

    public RagdollAutoConfiguration(RagdollProperties ragdollProperties) {
        this.ragdollProperties = ragdollProperties;
    }

    @Bean
    @ConditionalOnMissingBean(GlobalResponseProcessor.class)
    @ConditionalOnProperty(prefix = "veedo.ragdoll.global-advice", name = "enabled", havingValue = "true")
    public GlobalResponseProcessor generateCommonControllerAdvice() {
        String str = ragdollProperties.getGlobalAdvice().getIgnoreMethods();
        GlobalResponseProcessor advice = new GlobalResponseProcessor();
        if (StrUtil.isNotBlank(str)) {
            advice.setIgnoreMethods(str.split(","));
        }
        String basePackages = ragdollProperties.getGlobalAdvice().getBasePackages();
        if (StrUtil.isNotBlank(basePackages)) {
            advice.setBasePackages(basePackages.split(","));
        }
        return advice;
    }

    @Bean
    @ConditionalOnMissingBean(ExceptionProcessor.class)
    @ConditionalOnProperty(prefix = "veedo.ragdoll.exception-advice", name = "enabled", havingValue = "true")
    public ExceptionProcessor generateExceptionControllerAdvice() {
        ExceptionProcessor advice = new ExceptionProcessor();
        PrintMode mode = ragdollProperties.getExceptionAdvice().getMode();
//        if (StrUtil.isBlank(mode)) {
//            throw new NullPointerException("统一异常处理打印异常模式（mode）为空");
//        }
//        if (!mode.equalsIgnoreCase("log") && !mode.equalsIgnoreCase("stack")) {
//            throw new IllegalArgumentException("统一异常处理打印异常模式（mode）的值范围：[log, stack]");
//        }
        if (mode != PrintMode.LOG && mode != PrintMode.STACK) {
            throw new IllegalArgumentException("统一异常处理打印异常模式（mode）的值范围：[log, stack]");
        }
        advice.setMode(mode);
        advice.setShowRealErrorMessage(ragdollProperties.getExceptionAdvice().getShowRealErrorMessage());
        return advice;
    }

}
